package it.univaq.mwt.frontoffice.action;

import it.mwt.uivaq.utility.RssGenerator;
import it.univaq.mwt.business.NewsService;
import it.univaq.mwt.common.business.NewsServiceFactory;
import it.univaq.mwt.exceptionmonitor.WishlistUserException;
import it.univaq.mwt.model.entity.News;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.w3c.dom.Document;



public class ManageNewsAction extends MappingDispatchAction {
	
	public ActionForward showNewsList (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		
		HttpSession session = request.getSession();
		NewsServiceFactory newsFactory = NewsServiceFactory.getInstance();
		NewsService facadeNews = newsFactory.getNewsService();
								
		int id_news=0;
		List<News> news = null;
		
		if(request.getParameter("id")!=null){
			
			id_news=Integer.parseInt(request.getParameter("id").toString());
			News n=facadeNews.getNews(id_news);
			news=new ArrayList<News>();
			news.add(n);
			
			
		}else{
		
		news = facadeNews.getList(0, facadeNews.getNewsNumber());
		
		}
		request.setAttribute("newsList", news);
		request.setAttribute("actualpage", "news");
		
		if (session.getAttribute("id_group") != null) {
			return mapping.findForward("success");
		} else {
			return mapping.findForward("guest");
		}
	}

	public ActionForward showRss (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws IOException{
		
		RssGenerator rssGen=new RssGenerator();
		
		
		NewsServiceFactory newsFactory = NewsServiceFactory.getInstance();
		NewsService facadeNews = newsFactory.getNewsService();
								
		//da cambiare con un metodo seza limit
		List<News> news = null;
		
		news = facadeNews.getList(0, facadeNews.getNewsNumber());
		
	
		Document rssDoc=rssGen.getFeed(news, "news", "htp://wishlistr.com", "News rss", "en-us");
		String rss=rssGen.docToString(rssDoc);
		
		PrintWriter out = response.getWriter();
		out.print(rss);
		
		request.setAttribute("rss", rss);
		//return mapping.findForward("success");
		return null;
	}
}
